package com.metal.watch;

import java.io.IOException;
import java.util.Calendar;
import java.util.TimeZone;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class SilverServlet extends HttpServlet {

	private static final XMPPService xmpp = XMPPServiceFactory.getXMPPService();
	private static final DataKeeper dm = DataKeeperFactory.getInstance();

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		if (dm.isNoaction()) {// 周末不处理
			return;
		}

		String action = (String) req.getParameter("action");

		if (action != null && action.equals("init")) {
			// 每天7点前清零
			dm.setNow(0);
			dm.setLow(0);
			dm.setHigh(0);

			int weekend = Calendar.getInstance(
					TimeZone.getTimeZone("Asia/Shanghai")).get(
					Calendar.DAY_OF_WEEK);
			if (weekend == Calendar.SATURDAY || weekend == Calendar.SUNDAY) {
				dm.setNoaction(true);
			} else {
				dm.setNoaction(false);
			}

			return;
		}

		Document doc = null;

		try {
			doc = Jsoup.connect(Const.ICBC_URL).timeout(5000).get();
		} catch (IOException ex) {
			resp.getWriter().println(ex.getMessage());
		}

		if (doc != null) {
			float tmpN, tmpH, tmpL;
			String msgBody = "";
			Elements ele = doc.getElementById("GridView1")
					.getElementsContainingOwnText("人民币账户白银").first()
					.siblingElements();
			tmpN = toFloat(ele.get(3).text());
			tmpH = toFloat(ele.get(6).text()) - 0.02f;
			tmpL = toFloat(ele.get(7).text()) - 0.02f;

			if (action == null || action.equals("")) {

				if (dm.getNow() == 0) {// 如果为空，第一次，保存值

					dm.setNow(tmpN);
					dm.setLow(tmpL);
					dm.setHigh(tmpH);

				} else {// 比较基准值
					float High = dm.getNow() * 1.005f;
					float Low = dm.getNow() * 0.995f;

					msgBody = "!NOTICE: ";
					boolean dataChanged = false;
					if (tmpN >= High) {
						msgBody += "↑ N:" + tmpN + " > B:" + dm.getNow() + "\n";
						dataChanged = true;
					}
					if (tmpN <= Low) {
						msgBody += "↓ N:" + tmpN + " < B:" + dm.getNow() + "\n";
						dataChanged = true;
					}
					if (tmpH > dm.getHigh()) {
						msgBody += "N:" +tmpN+
								" ↑ H:" + tmpH + " > B:" + dm.getHigh()
								+ "\n";
						dataChanged = true;
					}
					if (tmpL < dm.getLow()) {
						msgBody += "N:" +tmpN+" ↓ L:" + tmpL + " < B:" + dm.getLow() + "\n";
						dataChanged = true;
					}

					if (dataChanged) {
						dm.setNow(tmpN);
						dm.setLow(tmpL);
						dm.setHigh(tmpH);

						sendMsg(msgBody);
					}
				}

			} else if (action.equals("fix")) {
				// 定时发送
				msgBody = "N:" + tmpN + " H:" + tmpH + " L:" + tmpL;
				sendMsg(msgBody);
			}

		}

	}

	private float toFloat(String s) {
		try {
			return Float.parseFloat(s);
		} catch (NumberFormatException ex) {
			return 0;
		}
	}

	private boolean sendMsg(String msgBody) {
		if (msgBody == "") {
			return false;
		}

		JID jid = new JID(Const.EMAIL);

		Message msg = new MessageBuilder().withRecipientJids(jid)
				.withBody(msgBody).build();

		boolean messageSent = false;

		if (xmpp.getPresence(jid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
		}

		return messageSent;
	}
}
